package com.allwees.core.mq.rabbitmq;

import com.allwees.core.mq.rabbitmq.config.RabbitMqConfig;
import com.allwees.core.mq.rabbitmq.config.RoutingInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;

/**
 *
 *
 * @author yangylsky
 * @since 2019-11-18
 *
 */
@Slf4j
public class MqUtil {
	private static RabbitMqConfig config;

	private static RabbitTemplate rabbitTemplate;

	public MqUtil(RabbitMqConfig config, RabbitTemplate rabbitTemplate) {
		MqUtil.config = config;
		MqUtil.rabbitTemplate = rabbitTemplate;
		rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
	}


	public static void send(MqEvent event) {
		String bizType = event.getBizType();
		if(StringUtils.isBlank(bizType)) {
			return;
		}
		RoutingInfo routingInfo = config.findRoutingInfo(event.getBizType());
		if(routingInfo == null) {
			log.warn("未找到与[{}]匹配的RoutingInfo", bizType);
			return;
		}
		MqUtil.send(routingInfo.getExchange(), event.getRoutingKey(), event.getSource());
	}

	public static void send(String exchange, String routingKey, Object msg) {
		if (StringUtils.isBlank(exchange)) {
			return;
		}
		rabbitTemplate.convertAndSend(exchange, routingKey, msg);
	}
}
